package com.wnxy.portal.config;

import com.wnxy.portal.common.constant.RedisConstant;
import com.wnxy.portal.entity.Book;
import com.wnxy.portal.model.vo.BookVo;
import com.wnxy.portal.service.IBookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class InitTop10CommandLineRunner implements CommandLineRunner {

    @Autowired
    private IBookService bookService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void run(String... args) throws Exception {
        // 在应用程序启动时执行的初始化逻辑: 数据预热
        List<Book> books = bookService.bookTop10();
        // 遍历books，放入redis的zset集合，buycount作为分值
        books.stream().map(book -> {
            BookVo bookVo = new BookVo();
            // 对象拷贝：参数1：数据源；参数2：目标
            BeanUtils.copyProperties(book,bookVo);
            return bookVo;
        }).forEach(bookVo -> {
            redisTemplate.opsForZSet().add(RedisConstant.BOOK_TOP10,bookVo,bookVo.getBuycount());
        });
    }
}